import { message } from 'antd';
import { getList, modifyHandleOk, deleteItem, handleSubmit } from '@/services/archsupplymanage';

export default {
  state: {
    formFieldsValue: {},
    pageData: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
  },

  effects: {
    *handleSubmit({ payload }, { call }) {
      const res = yield call(handleSubmit, payload);
      if (res.success) {
        message.success('新增成功！');
      } else {
        message.warning(res.message || '服务端错误');
      }
      return res;
    },
    *deleteItem({ payload }, { call }) {
      const res = yield call(deleteItem, payload);
      if (res.success) {
        message.success('删除成功！');
      } else {
        message.warning('删除失败！');
      }
      return res;
    },
    *modifyHandleOk({ payload }, { call }) {
      const res = yield call(modifyHandleOk, payload);
      if (res.success) {
        message.success('修改成功！');
      } else {
        message.error('修改失败！');
      }
      return res;
    },
    *getList({ payload }, { call, put }) {
      const res = yield call(getList, payload);
      const {
        pageArg: { currentPage, pageSize },
      } = payload;
      if (res.success) {
        yield put({
          type: 'updateList',
          payload: {
            data: res.data,
            currentPage,
            pageSize,
          },
        });
      } else {
        message.warning(res.message);
      }
      return res;
    },
  },

  reducers: {
    updateList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = data.pageRecords && Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        pageData: {
          list,
          pagination: { total: data.totalCount || 0, current: currentPage, pageSize },
        },
      };
    },
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};
